package com.quanshu.exchange.ui.gui.message.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.GroupMemberEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.message.chat.ChatActivity;
import com.quanshu.exchange.ui.gui.message.friends.SelectFriendActivity;
import com.quanshu.exchange.ui.gui.message.friends.UserDetailActivity;
import com.quanshu.exchange.ui.gui.message.group.dialog.DialogExitGroupChat;
import com.quanshu.exchange.ui.gui.qrcode.MyQrCodeActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/17.
 */

public class GroupChatDetailActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.group_avatar)
    ImageView groupAvatar;
    @BindView(R.id.group_name_text)
    TextView groupNameText;
    @BindView(R.id.group_desc)
    TextView groupDesc;
    @BindView(R.id.group_member_size)
    TextView groupMemberSize;
    @BindView(R.id.group_member_info)
    RecyclerView recyclerView;
    @BindView(R.id.group_check_members)
    RelativeLayout groupCheckMembers;
    @BindView(R.id.group_exit_btn)
    Button groupExitBtn;
    @BindView(R.id.group_member_layout)
    LinearLayout groupMemberLayout;
    @BindView(R.id.group_add_btn)
    Button groupAddBtn;
    @BindView(R.id.group_qrcode_layout)
    RelativeLayout groupQrcodeLayout;

    private SingleAdapter<GroupMemberEntity> adapter;
    private GroupEntity groupEntity;
    private List<GroupMemberEntity> allMember;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initListener();
        initData();
    }

    private void initIntent() {
        groupEntity = (GroupEntity) getIntent().getSerializableExtra("GroupEntity");
    }

    private void initView() {
        if (groupEntity != null) {
            GlideUtils.setRoundImageView(this, groupEntity.getGroup_photo(), R.drawable.default_group_avatar, groupAvatar);
            groupNameText.setText(groupEntity.getGroup_name());
            groupDesc.setText(groupEntity.getGroup_introduce());
            // 1是群成员 1不是
            if (groupEntity.getIs_have() == 0) {
                groupMemberLayout.setVisibility(View.GONE);
                groupAddBtn.setVisibility(View.VISIBLE);
                groupExitBtn.setVisibility(View.GONE);
            } else {
                groupMemberLayout.setVisibility(View.VISIBLE);
                groupAddBtn.setVisibility(View.GONE);
                groupExitBtn.setVisibility(View.VISIBLE);
            }
            recyclerView.setLayoutManager(new GridLayoutManager(this, 5));
            adapter = new SingleAdapter<>(new DataDisplayer<GroupMemberEntity>(this, R.layout.item_group_members_avatar) {
                @Override
                public void bindData(BaseViewHolder holder, LayoutWrapper<GroupMemberEntity> wrapper, GroupMemberEntity item, int position) {
                    ImageView imageView = holder.getView(R.id.member_avatar);
                    if (groupEntity.getOwner().equals(currentUser.getMemberid()) && position == adapter.getItemCount() - 1) {
                        holder.setVisibility(R.id.member_name, View.GONE);
                        GlideUtils.setRoundImageView(GroupChatDetailActivity.this, null, R.drawable.chat_more_func, imageView);
                        imageView.setOnClickListener(view -> {
                            Intent intent = new Intent(GroupChatDetailActivity.this, SelectFriendActivity.class);
                            intent.putExtra("List<GroupMemberEntity>", (Serializable) allMember);
                            startActivityForResult(intent, 0x02);
                        });
                    } else {
                        if (item.getMemberid().equals(groupEntity.getOwner())) {
                            holder.setVisibility(R.id.group_owner, View.VISIBLE);
                        } else {
                            holder.setVisibility(R.id.group_owner, View.GONE);
                        }
                        holder.setRoundImageUrl(R.id.member_avatar, item.getPhoto(), R.drawable.default_avatar);
                        holder.setVisibility(R.id.member_name, View.VISIBLE);

                        UserEntity userEntity = UserDao.getInstance().query(item.getMemberid());
                        if (userEntity != null) {
                            holder.setVisibility(R.id.member_name, View.VISIBLE);
                            holder.setText(R.id.member_name, AppUtils.getUserName(userEntity));
                        } else {
                            holder.setVisibility(R.id.member_name, View.VISIBLE);
                            holder.setText(R.id.member_name, item.getNickname());
                        }
                        // 如果当前用户是群主
                        if (currentUser.getMemberid().equals(groupEntity.getOwner()) || item.getMemberid().equals(groupEntity.getOwner())) {
                            imageView.setOnClickListener(view -> goUserDetailActivity(item));
                        }
                    }
                }
            });
            recyclerView.setAdapter(adapter);
        }
    }

    private void initData() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getGroupMembers(AppUtils.getSignParams(String.valueOf(groupEntity.getGroup_id())), groupEntity.getGroup_id())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<GroupMemberEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<GroupMemberEntity>> response) {
                        allMember = new ArrayList<>(response.getInfo());
                        groupMemberSize.setText(response.getInfo().size() + "  人");
                        List<GroupMemberEntity> info;
                        if (groupEntity.getOwner().equals(currentUser.getMemberid())) {
                            info = response.getInfo();
                            if (info.size() > 20) {
                                info.subList(0, 18);
                            }
                            GroupMemberEntity entity = new GroupMemberEntity();
                            entity.setAddImage(R.drawable.chat_more_func);
                            info.add(entity);
                        } else {
                            info = response.getInfo();
                            if (info.size() > 20) {
                                info.subList(0, 19);
                            }
                        }
                        adapter.setData(info);
                    }
                });
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(groupAddBtn, aVoid -> doJoinGroup(groupEntity));
        RxViewHelper.getInstance().clicks(groupExitBtn, aVoid -> doExitGroup());
        RxViewHelper.getInstance().clicks(groupCheckMembers, aVoid -> goAllMemberActivity());
        RxViewHelper.getInstance().clicks(groupQrcodeLayout, aVoid -> goMyQrCodeActivity());
    }

    private void goMyQrCodeActivity() {

        Intent intent = new Intent(this, MyQrCodeActivity.class);
        intent.putExtra("type", 2);
        intent.putExtra("GroupEntity", groupEntity);
        startActivity(intent);
    }

    private void goAllMemberActivity() {
        Intent intent = new Intent(this, AllGroupMemberActivity.class);
        intent.putExtra("List<GroupMemberEntity>", (Serializable) allMember);
        intent.putExtra("GroupEntity", groupEntity);
        startActivityForResult(intent, 0x01);
    }

    private void doSyncService(GroupEntity groupEntity) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .joinGroup(AppUtils.getSignParams(currentUser.getMemberid(), groupEntity.getHx_groupid()), currentUser.getMemberid(), groupEntity.getHx_groupid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        Intent intent = new Intent(GroupChatDetailActivity.this, ChatActivity.class);
                        intent.putExtra("CHAT_TYPE", ChatConstant.CHAT_TYPE_GROUP);
                        intent.putExtra("conversationID", groupEntity.getHx_groupid());
                        startActivity(intent);
                    }
                });
    }

    private void doJoinGroup(GroupEntity groupEntity) {
        if (groupEntity.getIs_verify() == 1) {
            Intent intent = new Intent(this, SendGroupApplyActivity.class);
            intent.putExtra("GroupEntity", groupEntity);
            startActivity(intent);
        } else {
            doSyncService(groupEntity);
        }
    }

    private void doExitGroup() {
        // 如果是群主
        if (currentUser.getMemberid().equals(getGroupOwnerId())) {
            ToastHelper.toast("请先转移群主");
        } else {
            DialogExitGroupChat exitGroupChat = new DialogExitGroupChat(this);
            exitGroupChat.show();
            exitGroupChat.getDeleteSubject().subscribe(o -> doTask());
        }
    }

    private void doTask() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .deleteGroupMember(AppUtils.getSignParams(currentUser.getMemberid(), String.valueOf(groupEntity.getGroup_id()),
                        groupEntity.getHx_groupid()), currentUser.getMemberid(),
                        groupEntity.getGroup_id(), groupEntity.getHx_groupid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        Intent intent = getIntent();
                        intent.putExtra("exit", true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    private String getGroupOwnerId() {
        if (adapter != null && adapter.getData() != null) {
            for (GroupMemberEntity memberEntity : adapter.getData()) {
                if (memberEntity.getRelation_type() == 2) {
                    return memberEntity.getMemberid();
                }
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {
                initData();
            } else if (requestCode == 0x02) {
                List<String> beSelectedMember = (List<String>) data.getSerializableExtra("List<String>");
                doAddMembers(beSelectedMember);
            }
        }
    }

    private void doAddMembers(List<String> beSelectedMember) {
        if (beSelectedMember != null && beSelectedMember.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < beSelectedMember.size(); i++) {
                stringBuffer.append(beSelectedMember.get(i));
                if (i != beSelectedMember.size() - 1) {
                    stringBuffer.append(",");
                }
            }
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .addGroupMembers(AppUtils.getSignParams(groupEntity.getHx_groupid(), stringBuffer.toString()), groupEntity.getHx_groupid(), stringBuffer.toString())
                    .compose(new BaseTransformer<>(this, true, false))
                    .subscribe(new BaseObserver<BaseResponse>() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            initData();
                        }
                    });
        }
    }

    private void goUserDetailActivity(GroupMemberEntity memberEntity) {
        if (memberEntity != null) {
            NetClient.getInstance()
                    .getNetService(UserInterface.class)
                    .searchFriend(AppUtils.getSignParams(currentUser.getMemberid(), memberEntity.getMemberid()), currentUser.getMemberid(), memberEntity.getMemberid())
                    .compose(new BaseTransformer<>(this))
                    .subscribe(new BaseObserver<BaseResponse<UserEntity>>() {
                        @Override
                        public void onSuccess(BaseResponse<UserEntity> response) {
                            UserEntity userEntity = response.getInfo();
                            Intent intent = new Intent(GroupChatDetailActivity.this, UserDetailActivity.class);
                            intent.putExtra("UserEntity", userEntity);
                            startActivity(intent);
                        }
                    });
        }
    }
}
